from common_data import *
from permission import *
from twisted.web import xmlrpc
from twisted.python import log

class XMLRPC_EnvironmentResource( xmlrpc.XMLRPC ):
    _permissions = {
        'getEnvironmentByID':       PERMISSION_REQUIREMENT_GLOBAL_ADMIN,
        'getEnvironmentByName':     PERMISSION_REQUIREMENT_GLOBAL_ADMIN,
        'listEnvironments':         PERMISSION_REQUIREMENT_GLOBAL_ADMIN,
        'addEnvironment':           PERMISSION_REQUIREMENT_GLOBAL_ADMIN,
        'delEnvironment':           PERMISSION_REQUIREMENT_GLOBAL_ADMIN,        
    }
    
    def __init__(self):
        """ load config
        """
        log.msg( 'Environment resource init' )
        xmlrpc.XMLRPC.__init__(self)
        
    def xmlrpc_listEnvironments(self):
        """return list of environments"""
        
        try:
            environments = Environment.select( orderBy=Environment.q.id )
        except:
            log.err()
            return False
            
        return list( ( env.id, env.name ) for env in environments )
    
    xmlrpc_listEnvironments.signature = [['array']]
    
    def xmlrpc_getEnvironmentByName(self, environment_name ):
        """get environment by name"""
        
        if not str( environment_name ):
            raise xmlrpc.Fault( 123, 'invalid argument' )
        
        try:
            env = Environment.selectBy( name = str( environment_name ) ).getOne()
        except SQLObjectNotFound:
            raise xmlrpc.Fault( 123, 'environment not found' )
        except:
            log.err( 'could not retrieve environment. environment_name: %s' % str( environment_name ) )
            log.err()
            raise xmlrpc.Fault( 123, 'could not retrieve environment' )
                    
        return self.envResultToDict( env )
    
    xmlrpc_getEnvironmentByName.signature = [['array','string']]
    
    def xmlrpc_getEnvironmentByID(self, environment_id ):
        """get environment by id"""
        
        if not int( environment_id ):
            raise xmlrpc.Fault( 123, 'invalid argument' )
        
        environment = getEnvironmentById( environment_id )
                    
        return self.envResultToDict( environment )
    
    xmlrpc_getEnvironmentByID.signature = [['array','int']]
    
    def xmlrpc_addEnvironment(self, environment_name ):
        """add new environment"""
        
        if not str( environment_name ):
            raise xmlrpc.Fault( 123, 'invalid argument' )
        
        if Environment.select( Environment.q.name == str( environment_name ) ).count():
            raise xmlrpc.Fault( 123, 'and environment with that name already exists' )
        
        try:
            e = Environment( name = str( environment_name ) )
        except:
            log.err( 'could not create new environment: environment_name = %s' % str( environment_name ) )
            log.err()
            raise xmlrpc.Fault( 123, 'could not create environment' )
        
        return e.id
    
    xmlrpc_addEnvironment.signature = [['int','string']]
    
    def xmlrpc_delEnvironment(self, environment_id ):
        """remove existing environment"""
        
        if not int( environment_id ):
            raise xmlrpc.Fault( 123, 'invalid arguments' )
        
        env = getEnvironmentById( int( environment_id ) )
        
        try:
            e.destroySelf()
        except:
            log.err( 'could not destroy environment: environment_id = %d' % int( environment_id ) )
            log.err()
            raise xmlrpc.Fault( 123, 'could not delete environment' )
        
        return True
    
    xmlrpc_delEnvironment.signature = [['bool','int']]
        
    def envResultToDict(self, environment ):
            result = dict()
            result['id'] = environment.id
            result['name'] = environment.name
            result['creation_time'] = xmlrpc.DateTime( environment.creation_time ).value
            result['modified_time'] = xmlrpc.DateTime( environment.modified_time ).value
            result['redirected_rrs'] = list( rr.id for rr in environment.redirected_rrs )
            
            return result